import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Progress,
  Table,
  Tag,
  Space,
  Select,
  DatePicker,
  Tooltip,
  Empty,
  Spin
} from 'antd';
import {
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  RiseOutlined,
  FallOutlined,
  ClockCircleOutlined,
  FireOutlined,
  TrophyOutlined,
  UserOutlined,
  HeartOutlined,
  ThunderboltOutlined
} from '@ant-design/icons';
import { Line, Bar, Pie, Area } from '@ant-design/plots';
import { PromptTemplate } from '@/types/prompt';
import { promptService } from '@/services/prompt.service';
import './style.css';

const { RangePicker } = DatePicker;
const { Option } = Select;

interface PromptStats {
  promptId: string;
  usageCount: number;
  successRate: number;
  avgResponseTime: number;
  avgTokenCount: number;
  userRating: number;
  ratingCount: number;
  lastUsed: Date;
  createdAt: Date;
  trend: 'up' | 'down' | 'stable';
  trendPercent: number;
}

interface UsageTrend {
  date: string;
  count: number;
  successRate: number;
}

interface PopularPrompt {
  id: string;
  name: string;
  category: string;
  usageCount: number;
  successRate: number;
  rating: number;
}

interface PromptStatisticsProps {
  prompts?: PromptTemplate[];
  currentPromptId?: string;
  onLoadStats?: (promptId: string) => Promise<PromptStats>;
  onLoadTrends?: (promptId: string, range: [Date, Date]) => Promise<UsageTrend[]>;
  onLoadPopular?: (limit: number) => Promise<PopularPrompt[]>;
  className?: string;
}

const PromptStatistics: React.FC<PromptStatisticsProps> = ({
  prompts = [],
  currentPromptId,
  onLoadStats,
  onLoadTrends,
  onLoadPopular,
  className = ''
}) => {
  const [stats, setStats] = useState<PromptStats | null>(null);
  const [trends, setTrends] = useState<UsageTrend[]>([]);
  const [popularPrompts, setPopularPrompts] = useState<PopularPrompt[]>([]);
  const [loading, setLoading] = useState(false);
  const [timeRange, setTimeRange] = useState<'week' | 'month' | 'year'>('week');
  const [selectedPromptId, setSelectedPromptId] = useState<string | undefined>(currentPromptId);

  // 加载统计数据
  useEffect(() => {
    if (selectedPromptId && onLoadStats) {
      loadStats(selectedPromptId);
    }
  }, [selectedPromptId]);

  // 加载趋势数据
  useEffect(() => {
    if (selectedPromptId && onLoadTrends) {
      loadTrends(selectedPromptId);
    }
  }, [selectedPromptId, timeRange]);

  // 加载热门提示词
  useEffect(() => {
    if (onLoadPopular) {
      loadPopularPrompts();
    }
  }, []);

  const loadStats = async (promptId: string) => {
    setLoading(true);
    try {
      if (onLoadStats) {
        const data = await onLoadStats(promptId);
        setStats(data);
      } else {
        // Use real API service
        const statistics = await promptService.getStatistics(promptId);
        setStats({
          promptId,
          usageCount: statistics.totalUsage,
          successRate: statistics.successRate,
          avgResponseTime: statistics.averageResponseTime,
          avgTokenCount: 150, // Default value, should be included in API response
          userRating: statistics.userSatisfaction / 20, // Convert from 0-100 to 0-5
          ratingCount: 100, // Default value, should be included in API response
          lastUsed: new Date(),
          createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
          trend: 'stable' as const, // Should be calculated from trend data
          trendPercent: 0
        });
      }
    } catch (error) {
      console.error('Failed to load stats:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadTrends = async (promptId: string) => {
    try {
      if (onLoadTrends) {
        const now = new Date();
        const start = new Date();
        
        switch (timeRange) {
          case 'week':
            start.setDate(now.getDate() - 7);
            break;
          case 'month':
            start.setMonth(now.getMonth() - 1);
            break;
          case 'year':
            start.setFullYear(now.getFullYear() - 1);
            break;
        }
        
        const data = await onLoadTrends(promptId, [start, now]);
        setTrends(data);
      } else {
        // Use real API service - convert daily usage to trend format
        const statistics = await promptService.getStatistics(promptId);
        const trendData: UsageTrend[] = statistics.dailyUsage.map(item => ({
          date: item.date,
          count: item.count,
          successRate: statistics.successRate // Use overall success rate as default
        }));
        setTrends(trendData);
      }
    } catch (error) {
      console.error('Failed to load trends:', error);
    }
  };

  const loadPopularPrompts = async () => {
    try {
      if (onLoadPopular) {
        const data = await onLoadPopular(5);
        setPopularPrompts(data);
      } else {
        // Use real API service
        const topPrompts = await promptService.getTopPrompts('week');
        const popularData: PopularPrompt[] = topPrompts.map(item => ({
          id: item.prompt.id,
          name: item.prompt.name,
          category: item.prompt.category,
          usageCount: item.usage,
          successRate: 90, // Default value, should be included in API response
          rating: 4.5 // Default value, should be included in API response
        }));
        setPopularPrompts(popularData);
      }
    } catch (error) {
      console.error('Failed to load popular prompts:', error);
    }
  };

  // 使用趋势图配置
  const trendLineConfig = {
    data: trends,
    xField: 'date',
    yField: 'count',
    smooth: true,
    color: '#1890ff',
    point: {
      size: 3,
      shape: 'circle'
    },
    tooltip: {
      showMarkers: true
    },
    xAxis: {
      label: {
        formatter: (text: string) => {
          const date = new Date(text);
          return `${date.getMonth() + 1}/${date.getDate()}`;
        }
      }
    }
  };

  // 成功率趋势配置
  const successRateConfig = {
    data: trends,
    xField: 'date',
    yField: 'successRate',
    smooth: true,
    color: '#52c41a',
    yAxis: {
      min: 0,
      max: 100,
      label: {
        formatter: (v: string) => `${v}%`
      }
    },
    tooltip: {
      formatter: (datum: any) => ({
        name: '成功率',
        value: `${datum.successRate.toFixed(1)}%`
      })
    }
  };

  // 热门提示词表格列
  const popularColumns = [
    {
      title: '排名',
      key: 'rank',
      width: 60,
      render: (_: any, __: any, index: number) => (
        <span className={`rank-badge rank-${index + 1}`}>
          {index === 0 && <TrophyOutlined />}
          {index + 1}
        </span>
      )
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (name: string, record: PopularPrompt) => (
        <Space>
          <span>{name}</span>
          <Tag color="blue" style={{ fontSize: 10 }}>{record.category}</Tag>
        </Space>
      )
    },
    {
      title: '使用次数',
      dataIndex: 'usageCount',
      key: 'usageCount',
      render: (count: number) => (
        <span>
          <FireOutlined style={{ color: '#fa8c16', marginRight: 4 }} />
          {count.toLocaleString()}
        </span>
      )
    },
    {
      title: '成功率',
      dataIndex: 'successRate',
      key: 'successRate',
      render: (rate: number) => (
        <Progress
          percent={rate}
          size="small"
          strokeColor={rate >= 90 ? '#52c41a' : rate >= 80 ? '#1890ff' : '#faad14'}
          format={percent => `${percent}%`}
        />
      )
    },
    {
      title: '评分',
      dataIndex: 'rating',
      key: 'rating',
      render: (rating: number) => (
        <Space>
          <HeartOutlined style={{ color: '#ff4d4f' }} />
          <span>{rating.toFixed(1)}</span>
        </Space>
      )
    }
  ];

  return (
    <div className={`prompt-statistics ${className}`}>
      <Spin spinning={loading}>
        <Row gutter={[16, 16]}>
          {/* 选择器和时间范围 */}
          <Col span={24}>
            <Card>
              <Space>
                <Select
                  style={{ width: 200 }}
                  placeholder="选择提示词"
                  value={selectedPromptId}
                  onChange={setSelectedPromptId}
                >
                  {prompts.map(p => (
                    <Option key={p.id} value={p.id}>{p.name}</Option>
                  ))}
                </Select>
                <Select value={timeRange} onChange={setTimeRange}>
                  <Option value="week">最近一周</Option>
                  <Option value="month">最近一月</Option>
                  <Option value="year">最近一年</Option>
                </Select>
              </Space>
            </Card>
          </Col>

          {/* 核心指标 */}
          {stats && (
            <>
              <Col xs={24} sm={12} md={6}>
                <Card>
                  <Statistic
                    title="总使用次数"
                    value={stats.usageCount}
                    prefix={<ThunderboltOutlined />}
                    suffix={
                      stats.trend === 'up' ? (
                        <span style={{ color: '#52c41a', fontSize: 14 }}>
                          <RiseOutlined /> {Math.abs(stats.trendPercent).toFixed(1)}%
                        </span>
                      ) : stats.trend === 'down' ? (
                        <span style={{ color: '#ff4d4f', fontSize: 14 }}>
                          <FallOutlined /> {Math.abs(stats.trendPercent).toFixed(1)}%
                        </span>
                      ) : null
                    }
                  />
                </Card>
              </Col>
              <Col xs={24} sm={12} md={6}>
                <Card>
                  <Statistic
                    title="成功率"
                    value={stats.successRate}
                    precision={1}
                    suffix="%"
                    valueStyle={{ color: '#52c41a' }}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={12} md={6}>
                <Card>
                  <Statistic
                    title="平均响应时间"
                    value={stats.avgResponseTime}
                    precision={0}
                    suffix="ms"
                    prefix={<ClockCircleOutlined />}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={12} md={6}>
                <Card>
                  <Statistic
                    title="用户评分"
                    value={stats.userRating}
                    precision={1}
                    suffix={`/ 5 (${stats.ratingCount})`}
                    valueStyle={{ color: '#faad14' }}
                  />
                </Card>
              </Col>
            </>
          )}

          {/* 使用趋势图 */}
          <Col xs={24} lg={12}>
            <Card title="使用趋势" extra={<LineChartOutlined />}>
              {trends.length > 0 ? (
                <Line {...trendLineConfig} height={200} />
              ) : (
                <Empty description="暂无数据" />
              )}
            </Card>
          </Col>

          {/* 成功率趋势 */}
          <Col xs={24} lg={12}>
            <Card title="成功率趋势" extra={<BarChartOutlined />}>
              {trends.length > 0 ? (
                <Area {...successRateConfig} height={200} />
              ) : (
                <Empty description="暂无数据" />
              )}
            </Card>
          </Col>

          {/* 热门提示词排行 */}
          <Col span={24}>
            <Card
              title="热门提示词排行"
              extra={<PieChartOutlined />}
            >
              <Table
                columns={popularColumns}
                dataSource={popularPrompts}
                rowKey="id"
                pagination={false}
                size="small"
              />
            </Card>
          </Col>

          {/* 用户偏好分析 */}
          <Col span={24}>
            <Card title="用户偏好分析">
              <Row gutter={16}>
                <Col span={8}>
                  <div className="preference-item">
                    <div className="preference-label">最常用类别</div>
                    <Tag color="blue">专业写作</Tag>
                  </div>
                </Col>
                <Col span={8}>
                  <div className="preference-item">
                    <div className="preference-label">平均使用时长</div>
                    <span>3.5 分钟</span>
                  </div>
                </Col>
                <Col span={8}>
                  <div className="preference-item">
                    <div className="preference-label">活跃时段</div>
                    <span>14:00 - 18:00</span>
                  </div>
                </Col>
              </Row>
            </Card>
          </Col>
        </Row>
      </Spin>
    </div>
  );
};

export default PromptStatistics;